package com.liuzhigang.images;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.PostConstruct;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Controller
public class RandomImageController {

    private final ResourceLoader resourceLoader;

    @Value("${images.path}")
    private String imagesPath;

    private List<String> imageList;

    public RandomImageController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @PostConstruct
    public void init() throws IOException {
        imageList = Files.walk(Paths.get(imagesPath))
                .filter(Files::isRegularFile)
                .map(path -> "classpath:static/images/" + path.getFileName().toString())
                .collect(Collectors.toList());
    }

    @GetMapping("/images")
    public ResponseEntity<byte[]> getRandomImage() throws IOException {
        Random random = new Random();
        String randomImage = imageList.get(random.nextInt(imageList.size()));

        Resource resource = resourceLoader.getResource(randomImage);
        InputStream inputStream = resource.getInputStream();

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[16384];
        while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        buffer.flush();
        byte[] imageBytes = buffer.toByteArray();
        inputStream.close();

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, "image/jpeg");

        return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
    }

}
